import React, { Component } from 'react'
import styles from './index.less'
import { connect } from 'dva';
import MyTextContent  from '../util/MyTextContent'
import { Table, Icon, Input, Button, Modal, Divider, Popconfirm, DatePicker, Select, message } from 'antd';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import moment from 'moment';
import fetch from 'dva/fetch';
import { getData } from '@/utils/localData';
import { baseUrl } from '@/utils/settings';
moment.locale('zh-cn');
const Option = Select.Option;

@connect(({ smsRecord, loading }) => ({ 
    smsRecordList: smsRecord.smsRecordList, smsRecordListPage: smsRecord.smsRecordListPage, smsRecordListTotal: smsRecord.smsRecordListTotal,
    fetchSelMySmsRecordLoading: loading.effects['smsRecord/fetchSelMySmsRecord'],
    longTotal: smsRecord.longTotal,
    shortTotal: smsRecord.shortTotal,
    smsTotal: smsRecord.smsTotal
}))
export default class SmsRecordView extends Component {

    columns = [{
        title: '主题',
        dataIndex: 'theme',
        key: 'theme',
        fixed: 'left',
      },{
        title: '姓名',
        dataIndex: 'sendName',
        key: 'sendName',
        width: 100
      },{
        title: '电话号',
        dataIndex: 'telnum',
        key: 'telnum',
        width: 100
      },{
        title: '条',
        dataIndex: 'pcount',
        key: 'pcount',
        width: 80,
      },{
        title: '内容',
        dataIndex: 'content',
        key: 'content',
        width: 200,
        render: (text, record) =>(
            <MyTextContent text={text} length={27}/>
        )
      },{
        title: '发送时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 180,
        render: (updateTime, record) =>{
            if(updateTime){
                return moment(updateTime).format('YYYY-MM-DD HH:mm:ss');
            }
        }
      },{
        title: '网关响应时间',
        dataIndex: 'gatewayTime',
        key: 'gatewayTime',
        width: 180,
        render: (gatewayTime) =>{
            if(gatewayTime){
                return moment(gatewayTime).format('YYYY-MM-DD HH:mm:ss');
            }
        }
      },{
        title: '网关提交状态',
        dataIndex: 'exStatus',
        key: 'exStatus',
        width: 150,
      },{
        title: '网关返回状态',
        dataIndex: 'gatewayStatus',
        key: 'gatewayStatus',
        width: 150,
      },{
        title: '发送状态',
        dataIndex: 'status',
        key: 'status',
        width: 150,
        render: (status, record) =>{
            let state
            if(status === 0){
                state = (
                    <span>
                        待发送
                        <Icon type="clock-circle" 
                        style={{ color: '#108ee9' , marginLeft: 5}} 
                        onClick = {()=>{
                            this.setState({
                                reSendTimeVisible: true, 
                                reSendId: record.id,
                                reSendTime: moment(record.createTime)
                            })
                        }}
                        />
                    </span>
                )
            }
            if(status === 1){
                state = "发送中"
            }
            if(status === 2){
                state = "发送成功"
            }
            if(status === 3){
                state = "发送失败"
            }
            return state
        }
      },{
        title: '用户回复内容',
        dataIndex: 'replyMsg',
        key: 'replyMsg',
        width: 180,
        render: (text, record) =>{
            if (text !== null){
                return <MyTextContent text={text} length={11}/>
            }
            return text
        }
      },{
        title: '用户回复时间',
        dataIndex: 'replyTime',
        key: 'replyTime',
        width: 180,
        render: (replyTime) =>{
            if(replyTime){
                return moment(replyTime).format('YYYY-MM-DD HH:mm:ss');
            }
        }
      },{
        title: '发送渠道',
        dataIndex: 'smsType',
        key: 'smsType',
        width: 150,
        render: (smsType) =>{
            if(smsType === 1){
                return "平台"
            }
            if(smsType === 2){
                return "excel导入"
            }
            if(smsType === 3){
                return "接口调用"
            }
        }
      }, {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 150,
        render: (text, record) =>{
            if(record.status === 0){
                    return (
                        <div>
                        <span>
                            <Popconfirm title="确定要删除这个短信?" onConfirm={this.confirmForDel} okText="Yes" cancelText="No">
                                <a href="javascript:;" onClick = {()=>{
                                        this.setState({
                                            delId: record.id,
                                        });
                                    }}>删除</a>
                            </Popconfirm>
                        </span>
                        </div>
                    )
            }else{
                    return (
                        <div>
                        <span>
                            <Popconfirm title="确定要重新发送这个短信?" onConfirm={this.confirm} okText="Yes" cancelText="No">
                                <a href="javascript:;" onClick = {()=>{
                                        this.setState({
                                            reSendId: record.id,
                                        });
                                    }}>重新发送</a>
                            </Popconfirm>
                        </span>
                        </div>
                    )
            }
        }
      }];

    constructor(props) {
        super(props);
        this.state = {
            name:'', //姓名
            phone:'', //电话
            theme:'', //主题
            userName: '', //用户名
            channel:undefined, //渠道
            status:undefined, //状态
            startTime:null, //开始时间
            endTime:null, //结束时间
            reSendId:null, //重发的id
            delId:null,//删除的id
            reSendTime:null //重新设定发送时间

        };
    }

    confirm = () => {
        const { dispatch, smsRecordListPage } = this.props
        const { reSendId, name, phone, theme,
            channel, status, startTime, endTime} = this.state
        dispatch({
            type: 'smsRecord/fetchReSendById',
            payload: {
                id: reSendId,
                name: name,
                telNum: phone,
                theme: theme,
                smsType: channel,
                status: status,
                startTime: startTime,
                endTime: endTime,
                page: smsRecordListPage
            }
        })
    }

    confirmForDel = () => {
        const { dispatch, smsRecordListPage } = this.props
        const { delId, name, phone, theme,
            channel, status, startTime, endTime} = this.state
        dispatch({
            type: 'smsRecord/fetchDelTimerById',
            payload: {
                id: delId,
                name: name,
                telNum: phone,
                theme: theme,
                smsType: channel,
                status: status,
                startTime: startTime,
                endTime: endTime,
                page: smsRecordListPage
            }
        })
    }
    
    startTimeOnChange = (e) => {
        this.setState({
            startTime: e
        })
    }

    endTimeOnChange = (e) => {
        this.setState({
            endTime: e
        })
    }

    onChangeName = (e) => {
        this.setState({ name: e.target.value });
    }

    onChangeUserName = (e) => {
        this.setState({ userName: e.target.value });
    }

    onChangePhone = (e) => {
        this.setState({ phone: e.target.value });
    }

    onChangeTheme = (e) => {
        this.setState({ theme: e.target.value });
    }

    setPage = (e) =>{
        const { dispatch } = this.props
        const {
            name, phone, theme, userName,
            channel, status, startTime, endTime
        } = this.state
        dispatch({
            type: 'smsRecord/fetchSelMySmsRecord',
            payload: {
                page: e,
                name: name,
                telNum: phone,
                theme: theme,
                username: userName,
                smsType: channel,
                status: status,
                startTime: startTime,
                endTime: endTime
            }
        })
    }

    showModal = () => {
        this.setState({
          visible: true,
        });
      }
    
    handleOk = (e) => {
        const { name, theme, userName, phone, channel, status, startTime, endTime } = this.state
        const { dispatch, smsRecordListPage } = this.props
        this.setState({
            visible: false,
        });
        if(!name && !theme && !userName && !phone && !channel && !status && !startTime && !endTime){
            message.error("至少添加一个筛选条件");
            return
        }
        dispatch({
            type: 'smsRecord/fetchReSendForMy',
            payload: {
                name: name,
                telNum: phone,
                theme: theme,
                smsType: channel,
                status: status,
                startTime: startTime,
                endTime: endTime,
                page: smsRecordListPage
            }
        })
    }

    reSendTimeHandleOk = (e) => {
        const { name, theme, userName, phone, channel, status, startTime, endTime, reSendId, reSendTime } = this.state
        const { dispatch, smsRecordListPage } = this.props
        this.setState({
            reSendTimeVisible: false,
        });
        dispatch({
            type: 'smsRecord/fetchReSetSendTime',
            payload: {
                name: name,
                telNum: phone,
                theme: theme,
                smsType: channel,
                status: status,
                startTime: startTime,
                endTime: endTime,
                page: smsRecordListPage,
                id: reSendId,
                sendTime: reSendTime,
            }
        })
    }

    reSendTimeOnChange = (e) => {
        this.setState({
            reSendTime: e
        })
    }

    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }
    
    reSendTimeHandleCancel = () => {
        this.setState({
            reSendTimeVisible: false
        })
    }


    render() {
        const { name, theme, userName, phone, channel, status, startTime, endTime, reSendTime } = this.state
        const { smsRecordList, smsRecordListPage, smsRecordListTotal, fetchSelMySmsRecordLoading, shortTotal, longTotal, smsTotal } = this.props
        console.log("user渲染",this.props)
        
        return (
            <div>
                <div className = {styles.query}>
                    <div className = {styles.search}>
                        <div className = {styles.line}>
                            <div className = {styles.inputList}>
                                <Input
                                    className = {styles.input}
                                    placeholder="姓名"
                                    prefix={<Icon type="idcard" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                    value={name}
                                    onChange={this.onChangeName}
                                />
                                <Input
                                    className = {styles.input}
                                    placeholder="电话号"
                                    prefix={<Icon type="phone" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                    value={phone}
                                    onChange={this.onChangePhone}
                                />
                                <Input
                                    className = {styles.input}
                                    placeholder="主题"
                                    prefix={<Icon type="profile" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                    value={theme}
                                    onChange={this.onChangeTheme}
                                />
                                {/* <Input
                                    className = {styles.input}
                                    placeholder="用户名"
                                    prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                    value={phone}
                                    onChange={this.onChangeUserName}
                                /> */}
                            </div>
                            <div className = {styles.btnList}>
                                <Button 
                                    className = {styles.btn}
                                    type="primary"
                                    onClick = {()=>{
                                        const { dispatch } = this.props
                                        const {
                                            name, phone, theme, userName,
                                            channel, status, startTime, endTime
                                        } = this.state
                                        dispatch({
                                            type: 'smsRecord/fetchSelMySmsRecord',
                                            payload: {
                                                page: 1,
                                                name: name,
                                                telNum: phone,
                                                theme: theme,
                                                username: userName,
                                                smsType: channel,
                                                status: status,
                                                startTime: startTime,
                                                endTime: endTime
                                            }
                                        })
                                    }}>查询</Button>
                                <Button 
                                    className = {styles.btn}
                                    type="primary"
                                    onClick = {()=>{
                                        const {
                                            name, phone, theme, userName,
                                            channel, status, startTime, endTime
                                        } = this.state
                                        let qs = {
                                            name: name,
                                            telNum: phone,
                                            theme: theme,
                                            smsType: channel,
                                            status: status,
                                            startTime: startTime,
                                            endTime: endTime
                                        }
                                        let url = baseUrl + 'smsRecord/exportMySmsRecord'
                                        fetch(url,{
                                                method: 'POST',
                                                headers:{
                                                    "Authorization":'Bearer ' + getData("token"),
                                                    "Content-Type": "application/json"
                                                },
                                                body:JSON.stringify(qs)
                                            }
                                            ).then(res => res.blob().then(blob => {
                                                var filenameUri = res.headers.get('Content-Disposition');
                                                var filename = decodeURI(filenameUri)
                                                if (window.navigator.msSaveOrOpenBlob) {
                                                    navigator.msSaveBlob(blob, filename);
                                                }else {
                                                    var a = document.createElement('a'); 
                                                    var url = window.URL.createObjectURL(blob);   // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上) 
                                                    a.href = url; 
                                                    a.download = filename; 
                                                    a.click(); 
                                                    window.URL.revokeObjectURL(url);
                                                } 
                                          })); 
                                    }}>导出</Button>
                            </div>
                        </div>
                        <div className = {styles.line}>
                            <div className = {styles.inputList}>
                                <Select 
                                    className = {styles.input}
                                    placeholder={"发送渠道"}
                                    onSelect={(e)=>{
                                        this.setState({
                                            channel: e === channel? undefined:e
                                        })
                                    }}>
                                    <Option value={1}>平台</Option>
                                    <Option value={2}>excel导入</Option>
                                    <Option value={3}>接口调用</Option>
                                </Select>
                                <Select 
                                    className = {styles.input}
                                    placeholder={"发送状态"}
                                    onSelect={(e)=>{
                                        this.setState({
                                            status: e === status? undefined:e
                                        })
                                    }}>
                                    <Option value={0}>待发送</Option>
                                    <Option value={1}>发送中</Option>
                                    <Option value={2}>发送成功</Option>
                                    <Option value={3}>发送失败</Option>
                                </Select>
                                <DatePicker 
                                    className = {styles.input}
                                    placeholder="开始时间"
                                    value={startTime}
                                    locale={locale}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    onChange={this.startTimeOnChange}
                                    showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                                />
                                <DatePicker 
                                    className = {styles.input}
                                    placeholder="结束时间"
                                    value={endTime}
                                    locale={locale}
                                    format="YYYY-MM-DD HH:mm:ss"
                                    onChange={this.endTimeOnChange}
                                    showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                                />
                            </div>
                            <div className = {styles.btnList}>
                                <Button type="primary" 
                                    className = {styles.btn}
                                    onClick={this.showModal}>重发</Button>
                            </div>
                        </div>
                    </div>
                </div>
                <Divider />
                <div className = {styles.content}>
                    <Table 
                        loading={fetchSelMySmsRecordLoading}
                        columns={this.columns} 
                        dataSource={smsRecordList}
                        scroll={{ x: 2200}}
                        footer={() => '长短信共计 ['+ longTotal +'] 条 , 短短信共计 ['+ shortTotal +'] 条 , 共计 ['+ smsTotal +'] 条'}
                        pagination = {{
                            current: smsRecordListPage,
                            total: smsRecordListTotal,
                            onChange: this.setPage
                        }} />
                </div>
                <Modal
                    title="重新发送"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText={"重发"}
                    cancelText={"取消"}
                >   
                    <p>按照筛选条件重新发送短信。。</p>
                    {name?<p>名字： {name}</p>:null}
                    {theme?<p>主题： {theme}</p>:null}
                    {userName?<p>用户名： {userName}</p>:null}
                    {phone?<p>电话号： {phone}</p>:null}
                    {channel?<p>发送渠道： {channel===1?"平台":null}{channel===2?"excel导入":null}{channel===3?"接口调用":null}</p>:null}
                    {status?<p>发送状态： {status===0?"待发送":null}{status===1?"发送中":null}{status===2?"发送成功":null}{status===3?"发送失败":null}</p>:null}
                    {startTime?<p>{moment(startTime).format('YYYY-MM-DD HH:mm:ss')} 之后发送</p>:null}
                    {endTime?<p>{moment(endTime).format('YYYY-MM-DD HH:mm:ss')} 之前发送</p>:null}
                </Modal>
                <Modal
                    title="重新设定发送时间"
                    visible={this.state.reSendTimeVisible}
                    onOk={this.reSendTimeHandleOk}
                    onCancel={this.reSendTimeHandleCancel}
                    okText="确定"
                    cancelText="取消"
                    >   
                        设置发送时间：
                        <DatePicker 
                            value={reSendTime}
                            locale={locale}
                            format="YYYY-MM-DD HH:mm:ss"
                            onChange={this.reSendTimeOnChange}
                            showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                        />
                </Modal>
            </div>
        )
    }


    componentDidMount(){
        const { dispatch } = this.props
        dispatch({
            type: 'smsRecord/fetchSelMySmsRecord',
            payload: {page:this.props.smsRecordListPage}
        })
        // dispatch({
        //     type: 'count/fetchSelShortAndLongTotalByCurrentUser',
        //     payload: {}
        // })
    }
}
